import { getUserImNews } from '@/common/api/user.js';
export default {
	namespaced: true,
	state: {
		token: uni.getStorageSync('token'),
		tokenExpired: uni.getStorageSync('tokenExpired'),
		role: uni.getStorageSync('role'), //角色 user-用户 merchant-商户
		userInfo: {
			// mid: '5000200000000004',//fuyang的mid
			// mid: '5023331143000020', //lp01
			// mobile: 18582382827,
			// auth: true,
			// name: '我是小家伙1',
			// desc: '描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述',
			// avatar: 'https://img.book118.com/sr1/M00/18/2A/wKh2C2Mqu_uIQKXSAAAIehhky1YAAJokQFaepoAAAiS160.jpg'
		}
	},
	getters: {
		isTokenValid(state) {
			return !!state.token && state.tokenExpired > Date.now()
		}
	},
	mutations: {
		SET_TOKEN: (state, {
			token,
			tokenExpired = Date.now() + 24 * 60 * 60 * 1000 * 10 //默认10天
		}) => {
			state.token = token;
			state.tokenExpired = tokenExpired;
			uni.setStorageSync('token', token);
			uni.setStorageSync('tokenExpired', tokenExpired);
		},
		REMOVE_TOKEN: (state) => {
			state.token = '';
			state.tokenExpired = 0;
			state.userInfo = {};
			uni.removeStorageSync('token');
			uni.removeStorageSync('tokenExpired');
		},
		SET_USER_INFO: (state, userInfo) => {
			state.userInfo = userInfo;
			getImNews();
		},
		SET_ROLE: (state, role) => {
			state.role = role;
			uni.setStorageSync('role', role);
		}
	},
	actions: {}
}
/**
 * 获取用户的im消息的条数
 */
async function getImNews() {
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	if (['pages/index/index', 'pages/find/find', 'pages/task/task', 'pages/message/message', 'pages/mine/mine'].indexOf(page.route) > -1) {
		const res = await getUserImNews();
		const im_num = +res.data.unread_num;
		if (im_num > 0) {
			const text = im_num > 99 ? '99+' : (im_num + '');
			uni.setTabBarBadge({
				index: 3,
				text: text,
				fail() {}
			})
		} else {
			uni.removeTabBarBadge({
				index: 3
			})
		}
	}
	setTimeout(() => {
		getImNews();
	}, 5 * 1000)
}
